import { Injectable, Logger } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';

import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Role } from '../roles/entities/role.entity';
import { UserInfo } from '../../common/user-info/user-info.dto';
const logger = new Logger('user_service');

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User) private user: Repository<User>,
    @InjectRepository(Role) private roleRepository: Repository<Role>,
  ) {}
  async create(createUserDto: CreateUserDto) {
    const userinfo = createUserDto;
    logger.log(userinfo);
    const user = await this.user.findOne({
      where: {
        phone: userinfo.phone,
      },
    });
    logger.log(user);
    if (user) {
      return {
        code: 1,
        message: '该手机号已创建',
      };
    } else {
      userinfo.roles = await this.roleRepository.find({
        where: {
          roleNo: 'common',
        },
      });
      await this.user.save(userinfo);
      return {
        code: 200,
        message: '保存成功',
      };
    }
  }

  findAll() {
    return this.user.find({ relations: ['roles'] });
  }

  findOneByUserName(username: string) {
    return this.user
      .createQueryBuilder('user')
      .where('user.username = :username', { username })
      .addSelect('user.password')
      .getOne();
  }

  findOne(id: string) {
    return this.user.findOne({
      where: {
        id: id,
      },
      relations: ['roles'],
    });
  }

  update(id: string, updateUserDto: UpdateUserDto) {
    return this.user.update(id, updateUserDto);
  }

  remove(id: string) {
    return this.user.delete(id);
  }
}
